import 'package:flutter/cupertino.dart';
import 'package:kq_flutter_pad_widgets/resources/kq_pad_theme_colors.dart';
import 'package:kq_flutter_pad_widgets/widgets/divider/kq_pad_divider.dart';
import 'package:kq_flutter_pad_widgets/widgets/form/kq_header_item_view.dart';
import 'package:kq_flutter_core_widget/utils/toast_util.dart';
import 'package:kq_flutter_core_widget/utils/ex/list_ex.dart';
import 'package:kq_flutter_core_widget/utils/ex/string_ex.dart';
import '../resources/l10n/kq_pad_intl.dart';
import '../widgets/form/entity/kq_form_entity.dart';
import '../widgets/form/kq_edit_item_view.dart';
import '../widgets/form/kq_edit_upper_lower_item_view.dart';
import '../widgets/form/kq_empty_item_view.dart';
import '../widgets/form/kq_image_box_item_view.dart';
import '../widgets/form/kq_radio_item_view.dart';
import '../widgets/form/kq_select_item_view.dart';

/// 表单控件辅助工具类
class KqPadFormUtil {
  /// 渲染多个表单组件
  static List<Widget> renderFormWidgetList(List<KqPadFormEntity> entities) {
    if (entities.isEmpty) {
      return [];
    }
    return entities.map((e) => renderFormWidget(e)).toList();
  }

  /// 渲染多个表单组件，使用[Column]包起来，并自动补全顶部的border
  static Widget renderFormWidgetListWithBorder(List<KqPadFormEntity> entities) {
    if (entities.isEmpty) {
      return Container();
    }
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        const KqPadDivider(
          color: KqPadThemeColors.bgF0,
        ),
        ...entities.map((e) => renderFormWidget(e)).toList()
      ],
    );
  }

  /// 渲染单个表单组件
  static Widget renderFormWidget(KqPadFormEntity entity) {
    if (entity.itemType != null) {
      switch (entity.itemType!) {
        case ItemType.edit:
          return KqPadEditItemView(entity: entity);
        case ItemType.radio:
          return KqPadRadioItemView(entity: entity);
        case ItemType.select:
          return KqPadSelectItemView(entity: entity);
        case ItemType.header:
          return KqPadHeaderItemView(entity: entity);
        case ItemType.empty:
          return const KqPadEmptyItemView();
        case ItemType.editUpperLower:
          return KqPadEditUpperLowerItemView(entity: entity);
        case ItemType.imageBox:
          return KqPadImageBoxItemView(entity: entity);
      }
    }
    return Container();
  }

  /// 根据ItemId 查找KqPadFormEntity
  static KqPadFormEntity? findEntityByItemId(
      List<KqPadFormEntity> data, String itemId) {
    for (var value in data) {
      if (value.itemId == itemId) {
        return value;
      }
    }
    return null;
  }

  /// 根据contentKey或contentKeyForShow 查找KqPadFormEntity
  static KqPadFormEntity? findEntityByContentKeyOrContentKeyForShow(
      List<KqPadFormEntity> list,
      {String? contentKey,
      String? contentKeyForShow}) {
    KqPadFormEntity? entity;
    for (int i = 0; i < list.length; i++) {
      KqPadFormEntity item = list[i];
      if (contentKey != null) {
        if (contentKeyForShow != null) {
          if (item.contentKey == contentKey &&
              item.contentKeyForShow == contentKeyForShow) {
            entity = item;
            break;
          }
        } else {
          if (item.contentKey == contentKey) {
            entity = item;
            break;
          }
        }
      } else {
        if (contentKeyForShow != null) {
          if (item.contentKeyForShow == contentKeyForShow) {
            entity = item;
            break;
          }
        }
      }
    }
    return entity;
  }

  /// 查找List<KqPadFormEntity>中所有的itemIds对应的实体
  static List<KqPadFormEntity> findAllEntityByItemIds(
      List<KqPadFormEntity> data, List<String> itemIds) {
    List<KqPadFormEntity> list = [];
    for (var value in data) {
      for (var itemId in itemIds) {
        if (value.itemId == itemId) {
          list.add(value);
        }
      }
    }
    return list;
  }

  /// 根据标题 查找KqPadFormEntity
  static KqPadFormEntity? findEntityByTitle(
      List<KqPadFormEntity> data, String title) {
    for (var value in data) {
      if (value.title == title) {
        return value;
      }
    }
    return null;
  }

  /// 快捷设置实体类数组中itemId对应实体类的值
  static setValueForEntityByItemId({
    required List<KqPadFormEntity> list,
    required String itemId,
    String? valueForShow,
    String? valueForSubmit,
  }) {
    var item = findEntityByItemId(list, itemId);
    if (item != null) {
      item.valueForSubmit = valueForSubmit;
      item.valueForShow = valueForShow;
      item.updateWidget();
    }
  }

  /// 快捷设置实体类数组中itemId对应实体类的是否可编辑
  static setEditableByItemId({
    required List<KqPadFormEntity> list,
    required String itemId,
    bool? editable,
    bool? editableMask,
  }) {
    var item = findEntityByItemId(list, itemId);
    if (item != null) {
      if (editable != null) {
        item.editable = editable;
      }
      if (editableMask != null) {
        item.editableMask = editableMask;
      }
      item.updateWidget();
    }
  }

  /// 找到数组里[itemId]对应的Entity，并清空表单的数据
  static clearFormValueByItemId(List<KqPadFormEntity> list, String itemId) {
    var entity2 = KqPadFormUtil.findEntityByItemId(list, itemId);
    if (entity2 != null) {
      entity2.valueForShow = null;
      entity2.valueForSubmit = null;
      entity2.qty = entity2.minQty;
      entity2.updateWidget();
    }
  }

  /// 快捷清空实体类数组中itemId对应实体类的值，包括valueForShow，valueForSubmit
  static clearFormValueByItemIds(
      {required List<KqPadFormEntity> list, required List<String> itemIds}) {
    var items = findAllEntityByItemIds(list, itemIds);
    if (items.isNotEmpty) {
      for (var item in items) {
        item.valueForSubmit = null;
        item.valueForShow = null;
        item.qty = item.minQty;
        item.updateWidget();
      }
    }
  }

  /// 生成提交给后端的数据
  static Map<String, dynamic> getFormSubmitJson(List<KqPadFormEntity> data) {
    Map<String, dynamic> params = {};
    for (var entity in data) {
      if (entity.itemType != null) {
        switch (entity.itemType!) {
          case ItemType.edit:
          case ItemType.radio:
          case ItemType.select:
            if (entity.contentKey != null) {
              params[entity.contentKey!] = entity.valueForSubmit;
            }
            if (entity.contentKeyForShow != null) {
              params[entity.contentKeyForShow!] = entity.valueForShow;
            }
            break;
          case ItemType.imageBox:
            if (entity.contentKey != null) {
              params[entity.contentKey!] = entity.valueForSubmit;
            }
            break;
          case ItemType.editUpperLower:
            if (entity.contentKeyForChild.isNotNullOrEmpty) {
              for (int i = 0; i < entity.contentKeyForChild!.length; i++) {
                params[entity.contentKeyForChild![i]] =
                    entity.valuesForSubmit?[i];
              }
            }
            break;
          case ItemType.empty:
          case ItemType.header:
            break;
        }
        // 提交单位
        if (entity.contentKeyForUnit != null) {
          params[entity.contentKeyForUnit!] = entity.unit;
        }
      }
    }
    return params;
  }

  /// 从ImageUrl实体类中获取用于提交给[OssNativeUtil.uploadPics]的参数
  static List<Map<String, dynamic>> generateImageBoxOssParams(
      KqPadFormEntity entity) {
    var imgUrls = entity.imageUrls ?? [];
    List<Map<String, dynamic>> list = [];
    for (var imgUrl in imgUrls) {
      Map<String, dynamic> map = {};
      map['ossKey'] = imgUrl.valueForSubmit;
      map['filePath'] = imgUrl.url;
      map['uploadOk'] = imgUrl.uploadOk;
      list.add(map);
    }
    return list;
  }

  /// 通过[OssNativeUtil.uploadPics]返回结果更新图片上传结果
  static void updateImageBoxUploadStatus(
      KqPadFormEntity entity, List<Map<String, dynamic>>? uploadPics) {
    if (uploadPics == null || uploadPics.isEmpty) {
      return;
    }

    var imageUrls = entity.imageUrls;
    if (imageUrls == null || imageUrls.isEmpty) {
      return;
    }

    for (var img in imageUrls) {
      if (img.uploadOk) {
        continue;
      }

      for (var uploadPic in uploadPics) {
        if (img.valueForSubmit == uploadPic['ossKey']) {
          img.uploadOk = uploadPic['uploadOk'] ?? false;
          break;
        }
      }
    }
  }

  /// 检查oss上传是否没有全部成功，不成功则返回true
  /// 默认会自动提示[图片上传失败，请重试]，如果不想自动提示，则设置[showToast]=false
  static bool checkOssUploadFailed(List<Map<String, dynamic>>? result,
      {bool showToast = true}) {
    if (result == null) {
      return false;
    }
    for (var value in result) {
      var uploadOk = value['uploadOk'];
      if (!uploadOk) {
        KqToast.showNormal(KqPadIntl.currentResource.imgUploadFail);
        return true;
      }
    }
    return false;
  }

  /// 检查必填项是否填写，未填写自动弹出提示
  ///
  /// 用法：
  /// if(checkMustInputForm(data)) {
  ///    return;
  /// }
  /// 注意：
  /// invalidValueHint 目前仅用于[ItemType.addNumber]的选择数据校验，如果未选择则提示这个。
  /// scrollController 如果必填的数据未填写则滚动到该条位置。
  /// [ignoreInvisibleForm] 未显示的表单直接跳过，不判断是否必填
  ///
  static bool checkMustInputForm(List<KqPadFormEntity> data,
      {bool checkQty = false,
      bool Function(num qty)? isQtyValid,
      String? invalidValueHint,
      String? invalidQtyHint,
      bool ignoreInvisibleForm = false,
      ScrollController? scrollController}) {
    for (var entity in data) {
      if (ignoreInvisibleForm && !entity.visible) {
        continue;
      }
      if (entity.itemType != null) {
        switch (entity.itemType!) {
          case ItemType.edit:
            // case ItemType.editBottom:
            if (entity.mustInput &&
                entity.contentKey != null &&
                (entity.valueForShow == null || entity.valueForShow!.isEmpty) &&
                (entity.valueForSubmit == null ||
                    entity.valueForSubmit!.isEmpty)) {
              KqToast.showNormal(
                  KqPadIntl.currentResource.pleaseEnter + entity.title);
              if (scrollController != null) {
                entity.widgetState.location(scrollController);
              }
              return true;
            }
            break;
          case ItemType.select:
            if (entity.mustInput &&
                entity.contentKey != null &&
                (entity.valueForSubmit == null ||
                    entity.valueForSubmit!.isEmpty)) {
              KqToast.showNormal(
                  KqPadIntl.currentResource.pleaseChoose + entity.title);
              if (scrollController != null) {
                entity.widgetState.location(scrollController);
              }
              return true;
            }
            break;
          case ItemType.radio:
            if (entity.mustInput &&
                entity.contentKey != null &&
                (entity.valueForSubmit == null ||
                    entity.valueForSubmit!.isEmpty)) {
              KqToast.showNormal(
                  KqPadIntl.currentResource.pleaseChoose + entity.title);
              if (scrollController != null) {
                entity.widgetState.location(scrollController);
              }
              return true;
            }
            break;
          case ItemType.header:
            break;
          case ItemType.imageBox:
            if (entity.mustInput &&
                entity.contentKey != null &&
                (entity.imageUrls == null || entity.imageUrls!.isEmpty)) {
              KqToast.showNormal(
                  KqPadIntl.currentResource.pleaseChoose + entity.title);
              if (scrollController != null) {
                entity.widgetState.location(scrollController);
              }
              return true;
            }
            break;
          case ItemType.empty:
            break;
          case ItemType.editUpperLower:
            if (entity.mustInput && entity.contentKey != null) {
              if (entity.valuesForSubmit.isNullOrEmpty) {
                KqToast.showNormal(
                    KqPadIntl.currentResource.pleaseEnter + entity.title);
                if (scrollController != null) {
                  entity.widgetState.location(scrollController);
                }
                return true;
              }
              for (String? value in entity.valuesForSubmit!) {
                if (value.isNullOrEmpty) {
                  KqToast.showNormal(
                      KqPadIntl.currentResource.pleaseEnter + entity.title);
                  if (scrollController != null) {
                    entity.widgetState.location(scrollController);
                  }
                  return true;
                }
              }
              try {
                if (double.parse(entity.valuesForSubmit![0]!) >
                    double.parse(entity.valuesForSubmit![1]!)) {
                  KqToast.showNormal(
                      entity.title + KqPadIntl.currentResource.upperLowerTips);
                  if (scrollController != null) {
                    entity.widgetState.location(scrollController);
                  }
                  return true;
                }
              } catch (e) {
                KqToast.showNormal(
                    entity.title + KqPadIntl.currentResource.upperLowerTips);
                if (scrollController != null) {
                  entity.widgetState.location(scrollController);
                }
                return true;
              }
            }
            break;
        }
      }
    }
    return false;
  }
}
